﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Common
{
    public class SoftwareLock : IDisposable
    {
        string m_filename = "";
        string m_id = "";

        public SoftwareLock(string filename)
        {
            m_filename = filename;

            do
            {
                while (System.IO.File.Exists(m_filename + ".slock")) Application.DoEvents();

                m_id = DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK");
                FileHelper.WriteAllText(m_filename + ".slock", m_id);
            } while (!IsValid());
        }

        public bool IsValid()
        {
            return (System.IO.File.Exists(m_filename + ".slock") && FileHelper.ReadAllText(m_filename + ".slock") == m_id);
        }

        public void Dispose()
        {
            if (IsValid())
                System.IO.File.Delete(m_filename + ".slock");
        }
    }
}
